#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
微信公众号素材上传示例脚本
演示如何上传各种类型的素材
"""

import os
import sys
from wechat_token import WeChatTokenManager
from wechat_material import WeChatMaterialManager
from config import WECHAT_CONFIG

def upload_image_example():
    """上传图片素材示例"""
    print("\n=== 上传图片素材示例 ===")
    
    # 支持的图片格式：bmp/png/jpeg/jpg/gif，最大10MB
    image_files = [
        'example_image.jpg',
        'example_image.png', 
        'example_image.gif'
    ]
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    material_manager = WeChatMaterialManager(token_manager)
    
    for image_file in image_files:
        if os.path.exists(image_file):
            try:
                print(f"\n正在上传图片: {image_file}")
                result = material_manager.upload_permanent_material(
                    file_path=image_file,
                    material_type='image'
                )
                print(f"✅ 上传成功!")
                print(f"   Media ID: {result.get('media_id')}")
                print(f"   URL: {result.get('url', '无')}")
                
            except Exception as e:
                print(f"❌ 上传失败: {e}")
        else:
            print(f"⚠️  文件不存在: {image_file}")

def upload_video_example():
    """上传视频素材示例"""
    print("\n=== 上传视频素材示例 ===")
    
    # 支持的视频格式：MP4，最大10MB
    video_file = 'example_video.mp4'
    
    if not os.path.exists(video_file):
        print(f"⚠️  文件不存在: {video_file}")
        return
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    material_manager = WeChatMaterialManager(token_manager)
    
    try:
        print(f"正在上传视频: {video_file}")
        result = material_manager.upload_permanent_material(
            file_path=video_file,
            material_type='video',
            title='示例视频标题',
            introduction='这是一个示例视频，用于演示素材上传功能'
        )
        print(f"✅ 上传成功!")
        print(f"   Media ID: {result.get('media_id')}")
        
    except Exception as e:
        print(f"❌ 上传失败: {e}")

def upload_voice_example():
    """上传语音素材示例"""
    print("\n=== 上传语音素材示例 ===")
    
    # 支持的语音格式：mp3/wma/wav/amr，最大2MB，播放长度不超过60s
    voice_files = [
        'example_voice.mp3',
        'example_voice.wav'
    ]
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    material_manager = WeChatMaterialManager(token_manager)
    
    for voice_file in voice_files:
        if os.path.exists(voice_file):
            try:
                print(f"\n正在上传语音: {voice_file}")
                result = material_manager.upload_permanent_material(
                    file_path=voice_file,
                    material_type='voice'
                )
                print(f"✅ 上传成功!")
                print(f"   Media ID: {result.get('media_id')}")
                
            except Exception as e:
                print(f"❌ 上传失败: {e}")
        else:
            print(f"⚠️  文件不存在: {voice_file}")

def upload_thumb_example():
    """上传缩略图素材示例"""
    print("\n=== 上传缩略图素材示例 ===")
    
    # 支持的缩略图格式：JPG，最大64KB
    thumb_file = 'example_thumb.jpg'
    
    if not os.path.exists(thumb_file):
        print(f"⚠️  文件不存在: {thumb_file}")
        return
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    material_manager = WeChatMaterialManager(token_manager)
    
    try:
        print(f"正在上传缩略图: {thumb_file}")
        result = material_manager.upload_permanent_material(
            file_path=thumb_file,
            material_type='thumb'
        )
        print(f"✅ 上传成功!")
        print(f"   Media ID: {result.get('media_id')}")
        
    except Exception as e:
        print(f"❌ 上传失败: {e}")

def batch_upload_example():
    """批量上传素材示例"""
    print("\n=== 批量上传素材示例 ===")
    
    # 定义要上传的文件列表
    files_to_upload = [
        {'path': 'images/photo1.jpg', 'type': 'image'},
        {'path': 'images/photo2.png', 'type': 'image'},
        {'path': 'videos/demo.mp4', 'type': 'video', 'title': '演示视频', 'intro': '这是一个演示视频'},
        {'path': 'audio/sound.mp3', 'type': 'voice'},
        {'path': 'thumbnails/thumb.jpg', 'type': 'thumb'},
    ]
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    material_manager = WeChatMaterialManager(token_manager)
    
    uploaded_materials = []
    
    for file_info in files_to_upload:
        file_path = file_info['path']
        file_type = file_info['type']
        
        if not os.path.exists(file_path):
            print(f"⚠️  跳过不存在的文件: {file_path}")
            continue
        
        try:
            print(f"\n正在上传 {file_type} 素材: {os.path.basename(file_path)}")
            
            kwargs = {
                'file_path': file_path,
                'material_type': file_type
            }
            
            # 如果是视频，添加标题和简介
            if file_type == 'video':
                kwargs['title'] = file_info.get('title', '默认标题')
                kwargs['introduction'] = file_info.get('intro', '默认简介')
            
            result = material_manager.upload_permanent_material(**kwargs)
            
            uploaded_materials.append({
                'file_path': file_path,
                'type': file_type,
                'media_id': result.get('media_id'),
                'url': result.get('url')
            })
            
            print(f"✅ 上传成功! Media ID: {result.get('media_id')}")
            
        except Exception as e:
            print(f"❌ 上传失败: {e}")
    
    # 输出上传结果汇总
    if uploaded_materials:
        print("\n=== 上传结果汇总 ===")
        for material in uploaded_materials:
            print(f"文件: {os.path.basename(material['file_path'])}")
            print(f"类型: {material['type']}")
            print(f"Media ID: {material['media_id']}")
            if material['url']:
                print(f"URL: {material['url']}")
            print("-" * 50)

def upload_tepian():
    """上传tepian.png图片"""
    print("\n=== 上传tepian.png图片 ===")
    
    tepian_file = 'src/tepian.png'
    
    if not os.path.exists(tepian_file):
        print(f"❌ 文件不存在: {tepian_file}")
        return
    
    # 检查文件大小
    file_size = os.path.getsize(tepian_file)
    print(f"📁 文件大小: {file_size / 1024:.1f} KB")
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    material_manager = WeChatMaterialManager(token_manager)
    
    try:
        print(f"🚀 正在上传图片: {tepian_file}")
        result = material_manager.upload_permanent_material(
            file_path=tepian_file,
            material_type='image'
        )
        print(f"✅ 上传成功!")
        print(f"   📋 Media ID: {result.get('media_id')}")
        print(f"   🔗 图片URL: {result.get('url', '无')}")
        
        # 保存结果到文件
        import json
        with open('tepian_upload_result.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        print(f"   💾 结果已保存到: tepian_upload_result.json")
        
    except Exception as e:
        print(f"❌ 上传失败: {e}")

def create_tepian_draft():
    """使用tepian素材创建草稿"""
    print("\n=== 使用tepian素材创建草稿 ===")
    
    # 使用已知的素材ID
    TEPIAN_MEDIA_ID = "loZScAtjldzC9kSbORaEJkBk_yVKFTM0m7DHhxNPwA1vSPncW7aIPsAJb-NgG6wr"
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    
    try:
        import requests
        
        print(f"📋 使用素材ID: {TEPIAN_MEDIA_ID}")
        
        # 获取access token
        access_token = token_manager.get_access_token()
        
        # 构建草稿数据
        draft_data = {
            "articles": [
                {
                    "article_type": "news",
                    "title": "欢迎关注我们！",
                    "author": "团队",
                    "digest": "感谢关注，提供优质内容",
                    "content": """<p>感谢您关注我们的微信公众号！</p>
<p>我们将为您提供最新的资讯和优质的内容。</p>
<p>如果您有任何问题或建议，欢迎随时与我们联系。</p>
<p><strong>让我们一起成长，一起进步！</strong></p>""",
                    "content_source_url": "",
                    "thumb_media_id": TEPIAN_MEDIA_ID,
                    "need_open_comment": 1,
                    "only_fans_can_comment": 0
                }
            ]
        }
        
        # 发送请求创建草稿
        url = "https://api.weixin.qq.com/cgi-bin/draft/add"
        params = {'access_token': access_token}
        
        print("🚀 正在创建草稿...")
        
        response = requests.post(url, params=params, json=draft_data, timeout=30)
        response.raise_for_status()
        
        result = response.json()
        
        if 'errcode' in result and result['errcode'] != 0:
            print(f"❌ 创建草稿失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            return
        
        print(f"✅ 草稿创建成功!")
        print(f"📋 草稿Media ID: {result.get('media_id')}")
        
        # 保存结果
        import json
        with open('tepian_draft_result.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        print(f"💾 草稿结果已保存到: tepian_draft_result.json")
        
    except Exception as e:
        print(f"❌ 创建草稿失败: {e}")

def publish_tepian_draft():
    """发布tepian草稿"""
    print("\n=== 发布tepian草稿 ===")
    
    # 使用已知的草稿Media ID
    TEPIAN_DRAFT_MEDIA_ID = "loZScAtjldzC9kSbORaEJq4zH4ogqJdncKHPo3A78i-I2aXEyMzEoFbIw3qnwzV3"
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    
    try:
        import requests
        
        print(f"📋 使用草稿Media ID: {TEPIAN_DRAFT_MEDIA_ID}")
        
        # 获取access token
        access_token = token_manager.get_access_token()
        
        # 发布草稿数据
        publish_data = {
            "media_id": TEPIAN_DRAFT_MEDIA_ID
        }
        
        # 发送请求发布草稿
        url = "https://api.weixin.qq.com/cgi-bin/freepublish/submit"
        params = {'access_token': access_token}
        
        print("🚀 正在发布草稿...")
        
        response = requests.post(url, params=params, json=publish_data, timeout=30)
        response.raise_for_status()
        
        result = response.json()
        
        if 'errcode' in result and result['errcode'] != 0:
            error_messages = {
                48001: "API功能未授权，请确认公众号已获得该接口权限",
                53503: "该草稿未通过发布检查，请检查草稿信息",
                53504: "需前往公众平台官网使用草稿",
                53505: "请手动保存成功后再发表"
            }
            error_msg = error_messages.get(result['errcode'], result.get('errmsg', '未知错误'))
            print(f"❌ 发布草稿失败: {result['errcode']} - {error_msg}")
            return
        
        print(f"✅ 发布任务提交成功!")
        print(f"📋 发布任务ID: {result.get('publish_id')}")
        print(f"📄 消息数据ID: {result.get('msg_data_id')}")
        print(f"⚠️  注意: 发布任务已提交，实际发布完成需要一定时间")
        
        # 保存发布结果
        import json
        with open('tepian_publish_result.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        print(f"💾 发布结果已保存到: tepian_publish_result.json")
        
        print(f"\n💡 发布说明:")
        print(f"- 发布任务已成功提交到微信服务器")
        print(f"- 实际发布完成需要等待微信审核（通常几分钟内）")
        print(f"- 发布完成后会收到事件推送通知")
        print(f"- 可以在微信公众平台后台查看发布状态")
        
    except Exception as e:
        print(f"❌ 发布草稿失败: {e}")

def delete_published_article():
    """删除已发布的文章"""
    print("\n=== 删除已发布的文章 ===")
    
    # 注意：删除需要使用article_id，而不是publish_id
    # article_id是发布完成后在事件推送中返回的，这里我们暂时无法获取
    # 实际使用时需要从发布完成的事件推送中获取article_id
    
    print("⚠️  重要说明:")
    print("- 删除文章需要使用 article_id（不是 publish_id）")
    print("- article_id 在发布完成后通过事件推送获取")
    print("- 当前发布任务ID: 2247483653")
    print("- 请等待发布完成后获取 article_id")
    
    # 演示如何使用（需要实际的article_id）
    DEMO_ARTICLE_ID = "your_article_id_here"  # 这需要从事件推送中获取
    
    if DEMO_ARTICLE_ID == "your_article_id_here":
        print("\n📝 使用方法:")
        print("1. 等待发布完成（通常几分钟内）")
        print("2. 从事件推送或公众平台获取 article_id")
        print("3. 将 article_id 填入代码中")
        print("4. 运行删除命令")
        return
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    
    try:
        import requests
        
        print(f"📋 使用Article ID: {DEMO_ARTICLE_ID}")
        
        # 获取access token
        access_token = token_manager.get_access_token()
        
        # 删除文章数据
        delete_data = {
            "article_id": DEMO_ARTICLE_ID,
            "index": 1  # 删除第一篇文章，0或不填则删除全部文章
        }
        
        # 发送请求删除文章
        url = "https://api.weixin.qq.com/cgi-bin/freepublish/delete"
        params = {'access_token': access_token}
        
        print("🗑️ 正在删除文章...")
        
        response = requests.post(url, params=params, json=delete_data, timeout=30)
        response.raise_for_status()
        
        result = response.json()
        
        if 'errcode' in result and result['errcode'] != 0:
            error_messages = {
                48001: "API功能未授权，请确认公众号已获得该接口权限"
            }
            error_msg = error_messages.get(result['errcode'], result.get('errmsg', '未知错误'))
            print(f"❌ 删除文章失败: {result['errcode']} - {error_msg}")
            return
        
        print(f"✅ 文章删除成功!")
        print(f"⚠️  注意: 此操作不可逆，文章已永久删除")
        
        # 保存删除结果
        import json
        with open('tepian_delete_result.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        print(f"💾 删除结果已保存到: tepian_delete_result.json")
        
    except Exception as e:
        print(f"❌ 删除文章失败: {e}")

def get_publish_status():
    """查询发布状态"""
    print("\n=== 查询发布状态 ===")
    
    # 使用已知的发布任务ID
    PUBLISH_ID = "2247483653"
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    
    try:
        import requests
        
        print(f"📋 查询发布任务ID: {PUBLISH_ID}")
        
        # 获取access token
        access_token = token_manager.get_access_token()
        
        # 查询状态数据
        status_data = {
            "publish_id": PUBLISH_ID
        }
        
        # 发送请求查询状态
        url = "https://api.weixin.qq.com/cgi-bin/freepublish/get"
        params = {'access_token': access_token}
        
        print("🔍 正在查询发布状态...")
        
        response = requests.post(url, params=params, json=status_data, timeout=30)
        response.raise_for_status()
        
        result = response.json()
        
        if 'errcode' in result and result['errcode'] != 0:
            print(f"❌ 查询发布状态失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            return
        
        # 解析发布状态
        status_messages = {
            0: "发布成功",
            1: "发布中",
            2: "原创失败", 
            3: "常规失败",
            4: "平台审核不通过",
            5: "成功后用户删除所有文章",
            6: "成功后系统封禁所有文章"
        }
        
        publish_status = result.get('publish_status', -1)
        status_text = status_messages.get(publish_status, "未知状态")
        
        print(f"📊 发布状态: {status_text} ({publish_status})")
        
        if publish_status == 0:  # 发布成功
            article_id = result.get('article_id')
            if article_id:
                print(f"📋 Article ID: {article_id}")
                print(f"💡 可以使用此 Article ID 来删除文章")
            
            if 'article_detail' in result:
                article_detail = result['article_detail']
                print(f"📰 文章数量: {article_detail.get('count', 0)}")
                for item in article_detail.get('item', []):
                    print(f"  文章 {item.get('idx')}: {item.get('article_url')}")
        elif publish_status in [2, 4]:  # 审核失败
            fail_idx_list = result.get('fail_idx', [])
            if fail_idx_list:
                print(f"❌ 失败的文章编号: {fail_idx_list}")
        
        # 保存状态查询结果
        import json
        with open('tepian_status_result.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        print(f"💾 状态结果已保存到: tepian_status_result.json")
        
        return result
        
    except Exception as e:
        print(f"❌ 查询发布状态失败: {e}")

def create_sample_files():
    """创建示例文件（用于测试）"""
    print("\n=== 创建示例文件 ===")
    
    # 创建目录
    os.makedirs('images', exist_ok=True)
    os.makedirs('videos', exist_ok=True)
    os.makedirs('audio', exist_ok=True)
    os.makedirs('thumbnails', exist_ok=True)
    
    print("✅ 已创建示例目录")
    print("请将您的素材文件放入对应目录：")
    print("  - images/ : 放入图片文件 (jpg, png, gif, bmp)")
    print("  - videos/ : 放入视频文件 (mp4)")
    print("  - audio/  : 放入音频文件 (mp3, wav, wma, amr)")
    print("  - thumbnails/ : 放入缩略图文件 (jpg, 64KB以下)")

def main():
    """主函数"""
    print("=== 微信公众号素材上传工具 ===")
    
    # 检查配置
    if WECHAT_CONFIG['APP_ID'] == 'your_app_id_here':
        print("❌ 请先在config.py中配置您的APP_ID和APP_SECRET")
        return
    
    if len(sys.argv) > 1:
        command = sys.argv[1]
        
        if command == 'image':
            upload_image_example()
        elif command == 'video':
            upload_video_example()
        elif command == 'voice':
            upload_voice_example()
        elif command == 'thumb':
            upload_thumb_example()
        elif command == 'batch':
            batch_upload_example()
        elif command == 'tepian':
            upload_tepian()
        elif command == 'draft':
            create_tepian_draft()
        elif command == 'publish':
            publish_tepian_draft()
        elif command == 'status':
            get_publish_status()
        elif command == 'delete':
            delete_published_article()
        elif command == 'init':
            create_sample_files()
        else:
            print_usage()
    else:
        print_usage()

def print_usage():
    """打印使用说明"""
    print("\n使用方法:")
    print("  python upload_material_example.py <command>")
    print("\n可用命令:")
    print("  init   - 创建示例目录结构")
    print("  image  - 上传图片素材示例")
    print("  video  - 上传视频素材示例")
    print("  voice  - 上传语音素材示例")
    print("  thumb  - 上传缩略图素材示例")
    print("  batch  - 批量上传素材示例")
    print("  tepian  - 上传tepian.png图片")
    print("  draft   - 使用tepian素材创建草稿")
    print("  publish - 发布tepian草稿")
    print("  status  - 查询发布状态")
    print("  delete  - 删除已发布的文章")
    print("\n素材格式要求:")
    print("  图片: 10MB以下, 支持 bmp/png/jpeg/jpg/gif")
    print("  语音: 2MB以下, 60秒以内, 支持 mp3/wma/wav/amr")
    print("  视频: 10MB以下, 支持 MP4")
    print("  缩略图: 64KB以下, 支持 JPG")

if __name__ == '__main__':
    main()
